from flask import Blueprint, jsonify, request
from sql.sql_operations import SQLOperations
from routes.payment.payment_route import  WeChatPayService  # 导入 payment_bp 和 WeChatPay
from models import execute_query
import xmltodict
import hashlib
import json
import time
import random
order_bp = Blueprint('order_bp', __name__)

class OrderStatus:
    STATUS_MAP = {
        1: '待支付',
        2: '已支付',
        3: '已完成',
        4: '已退款',
        5: '已取消',
        # Add more statuses as needed
    }

    @classmethod
    def get_status_description(cls, status_code):
        return cls.STATUS_MAP.get(status_code, 'Unknown Status')

def convert_user_id_to_open_id(user_id):
    # 这里实现将 user_id 转换为 open_id 的逻辑
    # 例如，从数据库中查询 open_id
    query = 'SELECT openid FROM course.users WHERE id = %s'
    result = execute_query(query, (user_id,), fetch=True)
    if result:
        return result[0][0]
    else:
        raise ValueError(f"User ID {user_id} not found or no open_id associated")

@order_bp.route('/api/order', methods=['PUT'])
def create_order():
    data = request.get_json()
    user_id = data.get('user_id')
    course_id = data.get('course_id')
    try:
        # 获取课程价格
        course = SQLOperations.get_course_detail(course_id)
        if not course:
            return jsonify({'message': 'Course not found'}), 404
        price = course['price']
        # 创建订单时设置 status 为 1（初始态）
        prefix = 'wmyjcc'
        timestamp = int(time.time())
        random_number = random.randint(1000, 9999)
        order_id = f"{prefix}{timestamp}{random_number}"
        order = SQLOperations.create_order(user_id, course_id,order_id, status=1)
        if not order:
            return jsonify({'message': 'Failed to create order'}), 400
        # 调用微信支付接口生成支付参数
        open_id = convert_user_id_to_open_id(user_id)
        wechat_pay = WeChatPayService()
        payment_info = wechat_pay.create_payment(
            order_id,
            open_id,
            amount=price
        )

        if not payment_info:
            return jsonify({'message': 'Failed to create payment'}), 400

        return jsonify({
            'message': 'Order created successfully',
            'order_id': order['id'],
            'user_id': order['user_id'],
            'course_id': order['course_id'],
            'order_date': order['created_at'],
            'status': order['order_status'],
            'payment_info': payment_info  # 返回微信支付信息
        }), 201

    except Exception as e:
        print(f'Error creating order: {str(e)}')
        return jsonify({'message': f'Error creating order: {str(e)}'}), 400

@order_bp.route('/api/orders/<int:order_id>/cancel', methods=['POST'])
def cancel_order(order_id):
    try:
        # 更新订单状态为 5（取消）
        query = '''
            UPDATE orders
            SET order_status = 5
            WHERE order_id = %s
        '''
        result = execute_query(query, (order_id,), fetch=False)

        if result:
            return jsonify({'message': 'Order cancelled successfully'}), 200
        else:
            return jsonify({'message': 'Failed to cancel order'}), 400

    except Exception as e:
        return jsonify({'message': f'Error cancelling order: {str(e)}'}), 400

@order_bp.route('/api/notify', methods=['POST'])
def handle_notify():
    # 获取微信支付的通知数据
    data = request.data.decode('utf-8')
    
    # 解析XML格式的数据（微信支付的通知通常为XML格式）
    xml_data = xmltodict.parse(data)
    xml_data = xml_data['xml']
    
    # 验证签名
    if not verify_sign(xml_data):
        return '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[Sign Error]]></return_msg></xml>'
    
    # 存储回调通知信息到数据库
    store_notification(xml_data)
    
    # 检查支付结果
    if xml_data.get('return_code') == 'SUCCESS' and xml_data.get('result_code') == 'SUCCESS':
        # 更新订单状态
        order_id = xml_data['out_trade_no']
        transaction_id = xml_data['transaction_id']
        
        # 调用 process_payment 更新订单状态
        wechat_pay = WeChatPayService()
        result = wechat_pay.process_payment(order_id, transaction_id)
        
        if result:
            return '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>'
        else:
            return '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[Process Payment Failed]]></return_msg></xml>'
    else:
        return '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[Payment Failed]]></return_msg></xml>'

def verify_sign(params):
    # 获取签名
    sign = params.pop('sign', '')
    
    # 重新生成签名
    sorted_params = sorted(params.items(), key=lambda item: item[0])
    stringA = '&'.join([f"{k}={v}" for k, v in sorted_params if v])
    stringSignTemp = f"{stringA}&key=your_api_key"  # 替换为你的 API 密钥
    generated_sign = hashlib.md5(stringSignTemp.encode('utf-8')).hexdigest().upper()
    
    # 比较签名
    return sign == generated_sign

def store_notification(notify_data):
    # 将回调通知数据存储到数据库
    query = '''
        INSERT INTO payment_notifications (order_id, transaction_id, notify_data)
        VALUES (%s, %s, %s)
    '''
    notify_json = json.dumps(notify_data)
    execute_query(query, (notify_data['out_trade_no'], notify_data['transaction_id'], notify_json), fetch=False)
@order_bp.route('/api/orders', methods=['GET'])
def get_orders():
    user_id = request.args.get('user_id')
    order_status = request.args.get('order_status', type=int)

    if not user_id:
        return jsonify({'message': 'user_id is required'}), 400

    try:
        # Construct the query based on the provided parameters
        query = '''
            SELECT 
                o.id, 
                o.user_id, 
                o.course_id, 
                o.order_id, 
                o.order_status, 
                o.created_at, 
                o.updated_at, 
                c.title AS course_name,
                c.price AS course_price,
                c.description AS course_description,
                c.category_id AS category_id
            FROM 
                course.orders o
            JOIN 
                course.courses c ON o.course_id = c.id
            WHERE 
                o.user_id = %s
        '''
        params = [user_id]

        if order_status is not None:
            query += ' AND o.order_status = %s'
            params.append(order_status)

        # Execute the query
        orders = execute_query(query, params, fetch=True)
        if not orders:
            return jsonify({'message': 'No orders found'}), 404

        orders_list = []
        for order in orders:
            order_dict = {
                'order_id': order[3],  # o.order_id
                'user_id': order[1],   # o.user_id
                'course_id': order[2], # o.course_id
                'order_date': order[5].strftime('%Y-%m-%d %H:%M:%S'),  # Format o.created_at
                'status': order[4],    # o.order_status
                'course_name': order[7],  # c.title
                'course_price': order[8], # c.price
                'course_description': order[9],  # c.description
                'order_status': OrderStatus.get_status_description(order[4]),
                'category_id': order[10]
            }
            orders_list.append(order_dict)

        return jsonify({
            'message': 'Orders retrieved successfully',
            'orders': orders_list
        }), 200

    except Exception as e:
        print(f'Error retrieving orders: {str(e)}')
        return jsonify({'message': f'Error retrieving orders: {str(e)}'}), 400